export default async function handler(req, res) {
  if (req.method !== 'POST') {
    return res.status(405).json({ error: 'Method not allowed' });
  }

  const { license_key, device_id } = req.body;

  // 配置信息 - 已经填好你的信息
  const FEISHU_APP_ID = "cli_a86c6ac6f478d013";
  const FEISHU_APP_SECRET = "cncPhnU5BMfKKWXJWCdhvdR8Pcx2Drb2";
  const FEISHU_APP_TOKEN = "S5L1bO9dsaKlArsrDMjcfkMXnAh";
  const FEISHU_LICENSES_TABLE_ID = "tbljohl3hkfNW8mc";
  const FEISHU_DEVICES_TABLE_ID = "tblRFSZiHBoCmiYE";

  try {
    // 第一步：获取访问令牌
    const tokenResponse = await fetch('https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        app_id: FEISHU_APP_ID,
        app_secret: FEISHU_APP_SECRET,
      }),
    });

    const tokenData = await tokenResponse.json();
    
    if (tokenData.code !== 0) {
      return res.json({ success: false, message: '获取访问令牌失败' });
    }

    const ACCESS_TOKEN = tokenData.tenant_access_token;

    // 第二步：查询授权码是否存在且有效
    const licenseUrl = `https://open.feishu.cn/open-apis/bitable/v1/apps/${FEISHU_APP_TOKEN}/tables/${FEISHU_LICENSES_TABLE_ID}/records?filter=AND(CurrentValue.[license_key]="${license_key}",CurrentValue.[is_active]=TRUE())`;
    
    const licenseResponse = await fetch(licenseUrl, {
      headers: {
        'Authorization': `Bearer ${ACCESS_TOKEN}`,
        'Content-Type': 'application/json',
      },
    });

    const licenseData = await licenseResponse.json();
    
    // 如果没找到记录，说明授权码无效
    if (!licenseData.data || licenseData.data.items.length === 0) {
      return res.json({ success: false, message: '授权码无效或已被禁用' });
    }

    const licenseRecord = licenseData.data.items[0];
    const record_id = licenseRecord.record_id;
    const fields = licenseRecord.fields;

    // 第三步：检查是否已经超过设备数量限制
    if (fields.devices_registered >= fields.max_devices) {
      return res.json({ success: false, message: '该授权码激活设备数已达上限' });
    }

    // 第四步：检查这个设备是否已经激活过
    const deviceCheckUrl = `https://open.feishu.cn/open-apis/bitable/v1/apps/${FEISHU_APP_TOKEN}/tables/${FEISHU_DEVICES_TABLE_ID}/records?filter=CurrentValue.[device_id]="${device_id}"`;
    
    const deviceCheckResponse = await fetch(deviceCheckUrl, {
      headers: {
        'Authorization': `Bearer ${ACCESS_TOKEN}`,
        'Content-Type': 'application/json',
      },
    });

    const deviceCheckData = await deviceCheckResponse.json();
    
    // 如果这个设备已经存在，直接返回成功
    if (deviceCheckData.data && deviceCheckData.data.items.length > 0) {
      return res.json({ success: true, message: '设备已验证' });
    }

    // 第五步：这个设备是新设备，进行激活
    // 5.1 在Devices表添加新记录
    const addDeviceUrl = `https://open.feishu.cn/open-apis/bitable/v1/apps/${FEISHU_APP_TOKEN}/tables/${FEISHU_DEVICES_TABLE_ID}/records`;
    
    await fetch(addDeviceUrl, {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${ACCESS_TOKEN}`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        fields: {
          "license_key": license_key,
          "device_id": device_id,
          "created_at": Date.now(),
        }
      }),
    });

    // 5.2 更新Licenses表的设备计数
    const updateLicenseUrl = `https://open.feishu.cn/open-apis/bitable/v1/apps/${FEISHU_APP_TOKEN}/tables/${FEISHU_LICENSES_TABLE_ID}/records/${record_id}`;
    
    await fetch(updateLicenseUrl, {
      method: 'PUT',
      headers: {
        'Authorization': `Bearer ${ACCESS_TOKEN}`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        fields: {
          "devices_registered": fields.devices_registered + 1,
        }
      }),
    });

    // 6. 全部成功，返回结果
    res.json({ 
      success: true, 
      message: `激活成功！这是第${fields.devices_registered + 1}台设备` 
    });

  } catch (error) {
    console.error('Verification error:', error);
    res.status(500).json({ success: false, message: '服务器错误' });
  }
}